import {
    _decorator,
    Component,
    Node,
    game,
    ImageAsset,
    Texture2D,
    SpriteFrame,
    director,
    Vec3,
    instantiate,
    Prefab,
    MeshRenderer,
    find,
    Canvas,
    Sprite,
    resources
} from 'cc';

const {ccclass, property} = _decorator;
import 'minigame-api-typings';
import 'three.js'
import {WebglBusiness} from "db://assets/scripts/ArUtil/WebglBusiness";

@ccclass('ARController')
export class ARController extends Component {
    private screenWidth: number;
    private screenHeight: number;
    private camera = null;
    private vk = null;
    private gl;//: WebGLRenderingContext | null = null;

    private  texture:Texture2D;

    @property(Node)
    openAR: Node;

    @property(SpriteFrame)
    arSpriteFrame: SpriteFrame = null;


    start() {


        const info = wx.getWindowInfo();
        this.screenWidth = info.screenWidth;
        this.screenHeight = info.screenHeight;

        // const model = instantiate(this.modelPrefab);
        // console.log("model =   ", model)
        // this.arModel.addChild(model);
        // model.setPosition(0, 0, 0);
        // model.setPosition(new Vec3(0, 0, 0));
        // director.getScene().addChild(model);


    }

    update(deltaTime: number) {

    }

    onOpenAr() {
        const _this = this;

        const arCanvas = find('ArCanvas').getComponent(Canvas);
        console.log('----------------------------canvas------------------------------');
        console.log(arCanvas);
        // const canvas = game.canvas as HTMLCanvasElement;
        // const context = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
        // this.gl = context as WebGLRenderingContext;
        // this.gl = new WebGLRenderingContext();
        this.vk = this.createVKSessionInstance();
        this.gl = this.vk.gl;

        console.log('======================open ar=========================');
        console.log('this.vk',this.vk);
        console.log('this.gl',this.gl);


        this.camera = wx.createCamera({
            width: _this.screenWidth,
            height:300,// _this.screenHeight,
            devicePosition: 'back',
            flash: 'off',
            size: 'small',
            success: res => {
                console.log('打开相机成功', res);


                // _this.camera.listenFrameChange();

                const spriteFrame = new SpriteFrame();
             
             console.log('-----------------------------sprite-------------------------------------');

                this.texture = new Texture2D();


                // const canvas = game.canvas as HTMLCanvasElement;
                // const context = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
                //
                //     _this.gl = context;//as WebGLRenderingContext;


                // this.vk.start(status => {
                //     if (status === 0  || status === null) {
                //         const onFrame = (timestamp: number) => {
                //             const vkFrame = this.vk.getVKFrame(_this.screenWidth, _this.screenHeight);
                //             if (vkFrame) {
                //                 renderARBackground(vkFrame);
                //             }
                //             this.vk.requestAnimationFrame(onFrame.bind(this));
                //         };
                //     } else {
                //         this.camera.destroy();
                //     }
                // });

                // const model = instantiate(this.modelPrefab);
                // console.log("model =   ", model)
                // this.arModel.addChild(model);
                // model.setPosition(0, 0, 0);
                // model.setPosition(new Vec3(0, 0, 0));
                // director.getScene().addChild(model);


                // const canvas = game.canvas;

                _this.vk.start(err => {
                    console.log('==vkSession start=====');
                    if(err){
                        console.log('vksession start error:',err)
                        return;
                    }

                    const onFrame = timestamp => {
                        console.warn('6666666666666666666666666666666666666666666666666666666666666666666   ',timestamp)
                        console.log('======_this.vk:',_this.vk)
                        const vkFrame = _this.vk.getVKFrame(_this.screenWidth, 300);
                        console.log("55555555555555555555555555555555555555555", vkFrame)
                        if (vkFrame) {
                            renderFrame(vkFrame);
                        }
                        _this.vk.requestAnimationFrame(onFrame);
                    }
                    _this.vk.requestAnimationFrame(onFrame);
                });
                //
                // // 3D 模型加载
                // const modelNode = instantiate(_this.modelPrefab);
                // console.log("model =   ", modelNode)
                // modelNode.setPosition(new Vec3(0, 0, 0));
                // director.getScene().addChild(modelNode);
            },
            fail: res => {
                console.log('打开相机失败', res);
                _this.camera.destroy();
            }
        });

        function updateSpriteFrame() {
            // 获取像素数据
            const imageData = this.texture._data; // Uint8Array（RGBA 格式）
            const len = imageData.length;

            // 更新纹理
            // this.texture.handleLoadedTexture();
            // this.displaySprite.spriteFrame = new SpriteFrame(this.texture);
        }




        function renderARBackground(vkFrame: any) {
            const { yTexture } = vkFrame.getCameraTexture(_this.gl);

            const meshRenderer = this.arBackground.getComponent(MeshRenderer)!;
            const material = meshRenderer.material!;
            const texture = new Texture2D();
            texture.reset({
                width: _this.screenWidth,
                height: _this.screenHeight,
                format: Texture2D.PixelFormat.RGBA8888
            });

            // 绑定 WebGLTexture 到 Cocos 的 texture
            (texture.getGFXTexture() as any)._glID = yTexture;

            material.setProperty('mainTexture', texture);
        }

        let isFirstWrite = true;
        function renderFrame(vkFrame) {

            try {
                console.warn("33333333333333333333333333333333333333333333")
                WebglBusiness.renderGL(vkFrame)
            }catch (e) {
                console.warn("44444444444444444444444444444444",e)
            }

        }

        this.camera.onAuthCancel(res => {
            console.log('用户未授权使用摄像头', res);
        });

        this.camera.onCameraFrame(frame => {
            // 不直接使用 frame 数据绘制，由 vk.getVKFrame 渲染
            console.log("***************************************",frame)
        });

        this.camera.onStop(res => {
            console.log('摄像头已停止:', res);
        });
    }


    stopAR() {
        if (this.camera) {
            this.camera.destroy();
            this.camera = null;
        }
        if (this.vk) {
            this.vk.stop();
            this.vk.destroy();
            this.vk = null;
        }
    }

    private createVKSessionInstance() {
        const isSupportV2 = wx.isVKSupport('v2');
        const vk = wx.createVKSession({
            track: {
                plane: {mode: isSupportV2 ? 3 : 1},
                marker: true,
                OSD: true
            },
            version: isSupportV2 ? 'v2' : 'v1',
        });
        // VKSession.init()
        console.log('============创建VKSession:', vk);
        return vk;
    }
}


